package com.jeeplus.modules.wxutil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import com.jeeplus.common.utils.IdGen;
import com.jeeplus.modules.anny.wxuser.entity.AnnyWxUser;
import com.jeeplus.modules.anny.wxuser.service.AnnyWxUserService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.UserMapper;
import com.jeeplus.modules.sys.service.SystemService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: Linzx
 * @Description:微信用户添加，实现
 * @Data: Created in 9:04 2018/10/23
 * @Modified By:
 */


@Controller
@RequestMapping(value = "/wxutil/WeiXinUserInfo")
public class WeiXinUserInfo {


    @Autowired
    private AnnyWxUserService annyWxUserService;


    @Autowired
    private SystemService systemService;

    private static Logger logger = Logger.getLogger(WeiXinUserInfo.class);
    //微信授权axxess_token路径
    public static final String WX_AUTH_LOGIN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    //微信获取用户授权路径
    public static final String WX_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    //AppId
    public static final String WX_APP_ID = "wx46db185dcc0e6107";
    //AppSecret
    public static final String WX_APP_KEY = "9753d0cfb338492a89409fd9ed46142c";

    /**
     * 这是获取微信openid进行用户注册的方法
     *
     * @param code
     * @return
     * @throws JSONException
     */
    @ResponseBody
    @RequestMapping(value = "getSessionKeyOropenid")
    public AnnyWxUser getSessionKeyOropenid(String code, HttpServletRequest request) throws JSONException {

        //获取授权 access_token
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append(WX_AUTH_LOGIN_URL).append("?appid=")
                .append(WX_APP_ID).append("&secret=")
                .append(WX_APP_KEY).append("&code=").append(code)
                .append("&grant_type=authorization_code");
        String loginRet = WeiXinUserInfo.get(loginUrl.toString());
        JSONObject grantObj = new JSONObject(loginRet);
        String errcode = grantObj.optString("errcode");
        if (!StringUtils.isEmpty(errcode)) {
            logger.error("login weixin error" + loginRet);
            return null;
        }
        String openId = grantObj.optString("openid");
        if (StringUtils.isEmpty(openId)) {
            logger.error("login weixin getOpenId error" + loginRet);
            return null;
        }

        String accessToken = grantObj.optString("access_token");
        String expiresIn = grantObj.optString("expires_in");
        String refreshToken = grantObj.optString("refresh_token");
        String scope = grantObj.optString("scope");

        //获取用户信息
        StringBuffer userUrl = new StringBuffer();
        userUrl.append(WX_USERINFO_URL).append("?access_token=").append(accessToken).append("&openid=").append(openId);
        String userRet = WeiXinUserInfo.get(userUrl.toString());
        JSONObject userObj = new JSONObject(userRet);
        AnnyWxUser userInfo = new AnnyWxUser();
        String uuid = IdGen.uuid();
        User user = new User();
        user.setId(uuid);
        user.setPassword(SystemService.entryptPassword("123456"));
        user.setIsNewRecord(true);
        List<AnnyWxUser> wxUsers = annyWxUserService.selectOpenID(openId);
        HttpSession session = request.getSession();

        //判断是否为空 为空则添加用户
        if (wxUsers.size() == 0) {
            userInfo.setWxOpenId(openId);
            userInfo.setLevel("1");
            userInfo.setBalance("0");
            userInfo.setWaitIntegral("0");
            userInfo.setBonus("0");
            userInfo.setEvaluate("0");
            userInfo.setUserID(uuid);
            systemService.insertUser(user);
            annyWxUserService.save(userInfo);
            return userInfo;
        } else {
            User sysUser = systemService.getUser(uuid);
            AnnyWxUser annyWxUser = wxUsers.get(0);
            session.setAttribute("sysUser", sysUser);
            session.setAttribute("annyWxUser", annyWxUser);
            return annyWxUser;
        }
    }

    /**
     * session获取当前对象
     * @param request
     * @return
     */
    public static AnnyWxUser getWxUser(HttpServletRequest request) {
        HttpSession httpSession = request.getSession();
        AnnyWxUser annyWxUser = (AnnyWxUser) httpSession.getAttribute("annyWxUser");
        return annyWxUser;
    }

    /**
     * session获取当前用户ID
     * @param request
     * @return
     */
    public static String getWxUserid(HttpServletRequest request) {
        HttpSession httpSession = request.getSession();
        AnnyWxUser annyWxUser = (AnnyWxUser) httpSession.getAttribute("annyWxUser");
        return annyWxUser.getUserID();
    }

    public static String get(String url) {
        String body = null;
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            logger.info("create httppost:" + url);
            HttpGet get = new HttpGet(url);
            get.addHeader("Accept-Charset", "utf-8");
            HttpResponse response = sendRequest(httpClient, get);
            body = parseResponse(response);
        } catch (Exception e) {
            logger.error("send post request failed: {}" + e.getMessage());
        }

        return body;
    }

    private static String paramsToString(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        try {
            for (String key : params.keySet()) {
                sb.append(String.format("&%s=%s", key, URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.toString())));
            }
        } catch (UnsupportedEncodingException e) {
            logger.warn("{}: encode url parameters failed" + e.getMessage());
        }
        return sb.length() > 0 ? "?".concat(sb.substring(1)) : "";
    }


    private static HttpResponse sendRequest(CloseableHttpClient httpclient, HttpUriRequest httpost)
            throws ClientProtocolException, IOException {
        HttpResponse response = null;
        response = httpclient.execute(httpost);
        return response;
    }


    private static String parseResponse(HttpResponse response) {
        logger.info("get response from http server..");
        HttpEntity entity = response.getEntity();

        logger.info("response status: " + response.getStatusLine());
        Charset charset = ContentType.getOrDefault(entity).getCharset();
        if (charset != null) {
            logger.info(charset.name());
        }

        String body = null;
        try {
            body = EntityUtils.toString(entity, "utf-8");
            logger.info("body " + body);
        } catch (IOException e) {
            logger.warn("{}: cannot parse the entity" + e.getMessage());
        }

        return body;
    }


}

